<template>
    <el-drawer v-model="drawer" :with-header="false" :size="drawerSize" @close="closeDrawer" :append-to-body="true"
        :modal="true" class="quotation-detail-drawer">
        <div class="project-detail">
            <div class="project-header">
                <div class="project-edit">
                    <template v-if="editVisible">
                        <el-button text type="primary" @click="submitOrder">提交</el-button>
                        <el-button text type="primary" @click="editVisible = false">取消</el-button>
                    </template>
                    <el-button text type="primary" :icon="Edit" v-else @click="convertEdit" />
                </div>
                <div class="project-title">
                    <el-input v-if="editVisible" v-model="editForm.title" size="small" style="width: 300px"
                        placeholder="请填写报价单主题" maxlength="64" clearable />
                    <template v-else>{{ quotationData.title }}</template>
                </div>
            </div>
            <div style="margin-left: 8%">
                <el-row style="line-height: 40px">
                    <el-col :span="4">客户：
                        <template v-if="editVisible">
                            <el-select v-model="editForm.customerId" size="small" style="width: 140px"
                                @change="supplierChange" clearable filterable>
                                <el-option v-for="item in customerList" :key="item.id" :value="item.id"
                                    :label="item.nickname" />
                            </el-select>
                        </template>
                        <template v-else>{{ quotationData.customerName }}</template>
                    </el-col>
                    <el-col :span="4">客户联系人：
                        <template v-if="editVisible">
                            <el-select v-model="editForm.contactId" size="small" style="width: 140px" @change="contactInfos"
                                clearable filterable>
                                <el-option v-for="item in contactList" :key="item.id" :value="item.id" :label="item.name" />
                            </el-select>
                        </template>
                        <template v-else>{{ quotationData.contactName }}</template>
                    </el-col>
                    <el-col :span="5">报价金额：
                        <template v-if="editVisible">
                            <el-input-number v-model="quotationData.amount" size="small" placeholder="请填写报价金额"
                                :max="99999999" :min="0" :precision="2" :controls="false" />
                            <el-checkbox style="margin-left: 10px" v-model="quotationData.amountTax" label="是否含税"
                                :true-label="1" :false-label="0" size="small" />
                        </template>
                        <span v-else>{{ quotationData.amount.toFixed(2) }} （{{ quotationData.amountTax == 1 ? '含税' : '不含税'
                        }}）</span>
                    </el-col>
                    <el-col :span="4">报价日期：
                        <span v-if="editVisible">
                            <el-date-picker v-model="editForm.quoteDate" style="width: 150px" type="date"
                                placeholder="请选择报价日期" value-format="YYYY-MM-DD" size="small" />
                        </span>
                        <span v-else>{{ quotationData.quoteDate }}</span>
                    </el-col>
                    <el-col :span="4" :offset="1">报价单归属人：{{ quotationData.userName }}</el-col>
                </el-row>
            </div>

            <el-row>
                <el-col :span="8">
                    <el-card :body-style="{ padding: `8px 10px` }" style="margin-right:10px;height: 100%" shadow="hover">
                        <el-row align="middle" class="row-cell" style="justify-content: center;">
                            <label class="label-tips" style="margin-right: 20px">订单辅助信息</label>
                            <div class="button-item" @click="openMaterial('doc')">
                                <el-icon color="var(--next-bg-menuBar-light-1)" size="16px">
                                    <ele-Document />
                                </el-icon>
                                <span class="tips">文档</span>
                                <span>0</span>
                            </div>
                            <div class="button-item" style="margin-left: 25px" @click="openMaterial('file')">
                                <el-icon color="var(--next-bg-menuBar-light-1)" size="16px">
                                    <ele-Link />
                                </el-icon>
                                <span class="tips">附件</span>
                                <span>0</span>
                            </div>
                        </el-row>
                        <el-row align="middle" class="row-cell">
                            <label class="label-tips">报价单号</label>
                            <div>{{ quotationData.quoteNo }}</div>
                        </el-row>
                        <el-row align="middle" class="row-cell">
                            <label class="label-tips">经办人</label>
                            <template v-if="editVisible">
                                <el-select v-model="editForm.contactId" size="small" placeholder="请选择经办人"
                                    style="width: 160px" @change="contactChange" filterable clearable>
                                    <el-option v-for="item in contactList" :key="item.id" :value="item.id"
                                        :label="item.name" />
                                </el-select>
                            </template>
                            <div v-else>
                                <template v-for="item in contactList" :key="item.id">
                                    <span v-if="item.memberId == quotationData.contactId">{{ item.name }}</span>
                                </template>
                            </div>
                        </el-row>
                        <el-row align="middle" class="row-cell">
                            <label class="label-tips">联系电话</label>
                            <el-input v-if="editVisible" v-model="editForm.contactPhone" style="width: 60%" size="small"
                                placeholder="请填写联系人电话" maxlength="16" clearable />
                            <div v-else>{{ quotationData.contactPhone }}</div>
                        </el-row>
                        <el-row align="middle" class="row-cell">
                            <label class="label-tips">交付说明</label>
                            <el-input v-if="editVisible" type="textarea" style="width: 60%" size="small"
                                v-model="editForm.submitExplain" :rows="2" />
                            <div v-else>{{ quotationData.submitExplain }}</div>
                        </el-row>
                        <el-row align="middle" class="row-cell">
                            <label class="label-tips">运输说明</label>
                            <el-input v-if="editVisible" type="textarea" style="width: 60%" size="small"
                                v-model="editForm.transportExplain" :rows="2" />
                            <div v-else>{{ quotationData.transportExplain }}</div>
                        </el-row>
                        <el-row align="middle" class="row-cell">
                            <label class="label-tips">包装说明</label>
                            <el-input v-if="editVisible" type="textarea" style="width: 60%" size="small"
                                v-model="editForm.packageExplain" :rows="2" />
                            <div v-else>{{ quotationData.packageExplain }}</div>
                        </el-row>
                    </el-card>
                </el-col>
                <el-col :span="16">
                    <el-card style="flex:1;height: 100%" :body-style="{ padding: `12px 0` }">
                        <el-row justify="space-between" align="middle" style="padding:0 10px">
                            <h4>产品清单</h4>
                            <el-row justify="end">
                                <el-button size="small" type="warning" @click="printData" :disabled="editVisible">
                                    <el-icon>
                                        <ele-Printer />
                                    </el-icon>
                                    打印
                                </el-button>
                                <el-button size="small" type="primary" @click="editProducts" :disabled="editVisible">
                                    <el-icon>
                                        <ele-EditPen />
                                    </el-icon>
                                    编辑
                                </el-button>
                            </el-row>
                        </el-row>
                        <div class="page-content" id="pageContainer">
                            <el-form ref="ruleRefForm" size="small" :model="quotationData" label-width="120px"
                                label-position="right" style="border: 1px solid var(--el-border-color-light)">
                                <el-table :data="quotationData.productList" size="small"
                                    :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
                                    <el-table-column label="产品编号" prop="id" width="160" />
                                    <el-table-column label="产品名称" prop="name" width="120" />
                                    <el-table-column label="数量" prop="quantity" width="90" />
                                    <el-table-column label="单价(元)" prop="price" width="90" />
                                    <el-table-column label="总价(元)" prop="total" width="90">
                                        <template #default="scope">
                                            <span style="color: red;">
                                                {{ (scope.row.quantity * scope.row.price).toFixed(2) }}
                                            </span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="型号" prop="ver" />
                                </el-table>
                                <el-form-item label="合计"
                                    style="margin-bottom:0;border-bottom:1px solid var(--el-border-color-light);font-size:14px;color:var(--el-color-danger)">￥{{
                                        countMoney(quotationData.productList) || '-' }}</el-form-item>
                                <el-form-item label="大写"
                                    style="margin-bottom:0;border-bottom:1px solid var(--el-border-color-light);font-weight:bold;font-size:14px;">{{
                                        numToChinese(countMoney(quotationData.productList) || 0) }}</el-form-item>
                                <el-form-item label="备注" style="margin-bottom:0">{{ quotationData.remark || '-'
                                }}</el-form-item>
                            </el-form>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <el-dialog v-model="productVisible" :close-on-click-modal="false" destroy-on-close width="60%"
            @close="productVisible = false" title="产品清单">
            <el-table :data="productsForm.productList" stripe :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }">
                <el-table-column label="序号" type="index" width="75" />
                <el-table-column label="产品名称" width="150" prop="name">
                    <template v-slot="{ row }">
                        <el-select v-model="row.name" allow-create size="small" filterable default-first-option clearable>
                            <el-option v-for="item in productList" :key="item.id" :value="item.name" :label="item.name" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="型号" width="150" prop="ver">
                    <template v-slot="{ row }">
                        <!-- <el-input v-model="row.ver" maxlength="64" size="small" clearable /> -->
                        {{ row.ver }}
                    </template>
                </el-table-column>
                <el-table-column label="详情/规格" width="150" prop="specs">
                    <template v-slot="{ row }">
                        <!-- <el-input v-model="row.specs" maxlength="255" size="small" clearable /> -->
                        {{ row.specs }}
                    </template>
                </el-table-column>
                <el-table-column label="数量" width="100" prop="quantity">
                    <template v-slot="{ row }">
                        <el-input-number v-model="row.quantity" :min="0" :max="999999" size="small" :controls="false"
                            style="width: 90%" @change="calAmount(row)" />
                    </template>
                </el-table-column>
                <el-table-column label="价格" width="130" prop="price">
                    <template v-slot="{ row }">
                        <!-- <el-input-number v-model="row.price" :min="0" :max="999999" size="small" :controls="false"
                            style="width: 90%" :precision="2" @change="calAmount(row)" /> -->
                        {{ row.price }}
                    </template>
                </el-table-column>
                <el-table-column label="小计" width="140" prop="total" >
                    <template #default="scope">
                        <span style="color: red;">
                            {{ (scope.row.quantity * scope.row.price).toFixed(2) }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark">
                    <template v-slot="{ row }">
                        <el-input v-model="row.remark" type="textarea" size="small" :rows="2" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="90">
                    <template v-slot="{ $index, row }">
                        <el-button type="danger" :icon="Delete" text @click="removeProduct($index, row)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row style="margin-top: 5px;width: 100%">
                <el-col :span="3" :offset="1">
                    <el-button type="primary" :icon="Plus" @click="addProduct" text>添加</el-button>
                </el-col>
                <el-col :span="4" style="line-height: 40px">合计：{{ countMoney(productsForm.productList) }} 元</el-col>
                <el-col :span="6" style="line-height: 40px">大写：{{ numToChinese(countMoney(productsForm.productList)) }}</el-col>
            </el-row>
            <template #footer>
                <el-button size="small" @click="productVisible = false">关 闭</el-button>
                <el-button size="small" type="primary" @click="productSubmit">保 存</el-button>
            </template>
        </el-dialog>

        <div class="tabs-list">
            <div class="close-btn" @click="drawer = false">
                <el-icon color="var(--next-color-white)" size="28px">
                    <ele-CircleClose />
                </el-icon>
            </div>
        </div>

        <product-list v-model:dialogDrawer="dialogProduct" @onSubmit="submitProduct"></product-list>
    </el-drawer>
</template>
  
<script>
import { computed, reactive, toRefs } from 'vue'
import { Edit, Plus, Delete } from '@element-plus/icons-vue'
import Cookies from 'js-cookie'
import { getDictByCodes } from '/@/api/sys/dict'
import { numToChinese } from '/@/utils/common'
import { ElMessage } from 'element-plus'
import ProductList from '/@/views/order/components/ProductList.vue'
import api from '/@/api/commonApi'

export default {
    name: 'QuotationDetail',
    emits: ['callback', 'update:drawer'],
    components: {
        ProductList
    },
    props: {
        drawer: {
            type: Boolean,
            default: false
        },
        quotation: {
            type: Object,
            default: {
                id: null,
                title: null,
                orderNo: null,
                userName: null,
                contactName: null
            }
        }
    },
    setup(props, context) {
        const { quotation } = toRefs(props)
        const quotationData = computed({
            get: () => {
                let quotationOrderId = quotation.value.id
                if (quotationOrderId) {
                    // 根据用户id获取用户在企业的名称
                    quotation.value.userName = Cookies.get('userName')
                    // 获取客户列表
                    api.customerList().then(res => {
                        state.customerList = res.data
                    })
                    contactInfos(quotation.value.customerId)
                    getDictByCodes(['orderSourceType']).then(res => state.dictMap = res.data).catch(e => console.log(e))
                }
                return quotation.value
            },
            set: val => context.emit('update:quotation', val)
        })
        const state = reactive({
            editVisible: false,
            editForm: {},
            dictMap: {
                orderSourceType: []
            },
            customerList: [],
            contactList: [],
            productsForm: {},
            tempId: 0,
            productVisible: false,
            productList: [],
            dialogProduct: false,
            drawerSize: document.body.clientWidth <= 1400 ? '1220px' : '85%'
        })

        // 打开文档doc/附件file对话框
        const openMaterial = (type) => {

        }
        // 打开编辑报价单的清单
        const editProducts = () => {
            // 获取产品清单名称
            state.productsForm = {
                id: quotationData.value.id,
                amount: quotationData.value.amount,
                productList: JSON.parse(JSON.stringify(quotationData.value.productList))
            }
            state.tempId = 0
            state.productVisible = true
        }
        // 移除产品行
        const removeProduct = (index, product) => {
            state.productsForm.productItems.splice(index, 1)
            state.productsForm.productAmountSum -= product.total
        }
        // 打印数据
        const printData = () => {

        }
        // 转换页面编辑状态
        const convertEdit = () => {
            state.editForm = JSON.parse(JSON.stringify(quotationData.value))
            state.editForm.productList = null
            state.editVisible = true
        }
        // 提交修改报价单
        const submitOrder = () => {
            api.editOrderQuote(state.editForm).then(res => {
                if (res.data) {
                    quotationData.value.title = state.editForm.title
                    quotationData.value.supplierInfoId = state.editForm.supplierInfoId
                    quotationData.value.shortName = state.editForm.shortName
                    quotationData.value.amount = state.editForm.amount
                    quotationData.value.quoteDate = state.editForm.quoteDate
                    quotationData.value.supplierInfoId = state.editForm.supplierInfoId
                    quotationData.value.contactId = state.editForm.contactUserId
                    quotationData.value.contactPhone = state.editForm.contactPhone
                    quotationData.value.contactName = state.editForm.contactName
                    quotationData.value.submitExplain = state.editForm.submitExplain
                    quotationData.value.transportExplain = state.editForm.transportExplain
                    quotationData.value.packageExplain = state.editForm.packageExplain
                    ElMessage.success('保存成功！')
                    state.editVisible = false
                }
            }).catch(e => console.log(e))
        }
        // 客户改变
        const supplierChange = (customerId) => {
            state.editForm.contactId = null
            state.editForm.contactPhone = null
            state.editForm.contactName = null
            for (let i = 0; i < state.customerList.length; i++) {
                let item = state.customerList[i]
                if (item.id == customerId) {
                    state.editForm.customerName = item.nickname
                    state.editForm.shortName = item.shortName
                    break
                }
            }
            contactInfos(customerId)
        }
        // 获取客户联系人
        const contactInfos = (customerId) => {
            api.getCustomerContacts({ memberId: customerId }).then(res => {
                state.contactList = res.data
                if (res.data.length > 0) {
                    let item = res.data[0]
                    state.editForm.contactId = item.id
                    state.editForm.contactPhone = item.phone
                    state.editForm.contactName = item.name
                }
            })
        }
        // 联系人改变
        const contactChange = (contactId) => {
            for (let i = 0; i < state.contactList.length; i++) {
                let item = state.contactList[i]
                if (item.id == contactId) {
                    state.editForm.contactPhone = item.phone
                    state.editForm.contactName = item.name
                    break
                }
            }
        }
        // 产品合计
        const calAmount = (product) => {
            let total = 0
            product.total = ((product.quantity || 0) * (product.price || 0)).toFixed(2)
            state.productsForm.productList.forEach(item => total += (item.quantity || 0) * (item.price || 0))
            state.productsForm.amount = total.toFixed(2)
        }
        // 添加模态框
        const addProduct = () => {
            state.dialogProduct = true
        }
        // 编辑报价单
        const productSubmit = () => {
            api.editOrderQuote(state.productsForm).then(res => {
                if (res.data) {
                    quotationData.value.productList = res.data.productList
                    quotationData.value.amount = res.data.amount
                    ElMessage.success('保存成功！')
                    state.productVisible = false
                }
            }).catch(e => console.log(e))
        }
        // 关闭详情页
        const closeDrawer = () => {
            context.emit('callback')
            context.emit('update:drawer', false)
        }
        // 计算金额
        const countMoney = (val) => {
            let money = 0;
            val.forEach(item => {
                money += item.price * item.quantity
            })
            return money;
        }
        // 获取选择的产品
        const submitProduct = val => {
            let list = []
            val.forEach(e => {
                let isExist = state.productsForm.productList.find(item => {
                    return item.productId == e.chooseSpec[0]
                })
                if (!isExist) {
                    let selSku = e.skuInfos.find(item => {
                        return item.skuId == e.chooseSpec[0]
                    })
                    list.push({
                        id: null,
                        quoteId: state.productsForm.id,
                        productId: selSku.skuId,
                        name: e.spuName,
                        ver: selSku.skuName,
                        specs: selSku.skuName,
                        quantity: 0,
                        price: selSku.price,
                        total: 0.00,
                        remark: null
                    })
                }
            })
            state.productsForm.productList = state.productsForm.productList.concat(list)
        }

        return {
            Edit,
            Plus,
            Delete,
            ...toRefs(state),
            closeDrawer,
            quotationData,
            openMaterial,
            numToChinese,
            editProducts,
            printData,
            convertEdit,
            submitOrder,
            supplierChange,
            contactChange,
            calAmount,
            addProduct,
            productSubmit,
            removeProduct,
            contactInfos,
            submitProduct,
            countMoney,
        }
    }
}
</script>
  
<style scoped lang="scss">
.project-detail {
    padding: 10px;
    background: var(--next-bg-main-color);
    min-height: 100%;

    .project-header {
        position: relative;
        display: flex;

        .project-title {
            width: 97%;
            text-align: center;
            font-size: 18px;
            font-weight: bold;
        }

        .project-edit {
            width: 3%;

            :deep(.el-icon) {
                font-size: 18px !important;
                margin-right: 0;
            }
        }
    }

    .button-item {
        display: flex;
        align-items: center;
        cursor: pointer;
        font-size: 12px;
        padding: 4px 6px;
        border-radius: 4px;
        border: 1px solid var(--el-color-primary-light-8);

        span {
            line-height: 20px;
            display: inline-block;
            margin-left: 8px;
            color: var(--next-bg-menuBar-light-1);
        }

        .tips {
            font-weight: bold;
            color: var(--next-bg-menuBar-light-1);
            margin-left: 2px;
        }

        &:hover {
            background: var(--el-color-primary-light-8);
        }
    }

    .label-tips {
        font-size: 12px;
        width: 100px;
        margin-right: 10px;
        display: block;
        text-align: right;
    }

    .row-cell {
        margin-bottom: 18px;

        &:first-child {
            margin-top: 18px;
        }

        .label-data {
            font-size: 12px;
            margin-right: 5px;
        }
    }

    .page-content {
        padding: 10px;

        :deep(.el-form) {
            border: 1px solid var(--el-border-color-light);
            margin-top: 10px;

            .el-form-item__label {
                border-right: 1px solid var(--el-border-color-light);
                height: 34px !important;
                line-height: 34px;
            }

            .el-form-item__content {
                padding-left: 10px;
            }

            .el-table__cell {
                border-right: 1px solid var(--el-border-color-light);
                box-sizing: border-box;

                &:last-child {
                    border-right: none;
                }
            }
        }
    }
}

.fixed-right {
    position: fixed;
    right: 40px;
    bottom: 30px;
    z-index: 999;

    .fixed-cell {
        background: var(--next-bg-topBar);
        border-radius: 50%;
        width: 60px;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        color: var(--el-color-primary);
        font-size: 32px;
        box-shadow: rgba(0, 0, 0, 0.1) 0 1px 3px 0, rgba(0, 0, 0, 0.06) 0 1px 2px 0;
        margin-top: 10px;
    }
}

.tabs-list {
    position: absolute;
    top: 90px;
    left: -50px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    overflow: auto;
    max-height: 100%;

    .close-btn {
        width: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        background: var(--el-color-primary);
        padding: 5px 0;
        border-radius: 5px 0 0 5px;
    }
}</style>
<style lang="scss">.quotation-detail-drawer {
    position: fixed;
    overflow: unset;
    background: var(--next-bg-main-color);
}</style>
  